package day08;

import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <a href="https://leetcode.cn/problems/maximum-number-of-balls-in-a-box/">1742. 盒子中小球的最大数量</a>
 * @author admin
 */
public class Answer {

    public static void main(String[] args) {
        Answer answer = new Answer();
        int i = answer.countBalls(1, 10);
        System.out.println(i);

        int i1 = answer.countBallsLeetCode(1, 10);
        System.out.println(i1);
    }

    public int countBalls(int lowLimit, int highLimit) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = lowLimit; i <= highLimit; i++) {
            int num = addAllNum(i);
            Integer integer = map.get(num);
            if (integer != null) {
                map.put(num, ++integer);
            } else {
                map.put(num, 1);
            }
        }
        List<Integer> list = map.values().stream().sorted((a, b) -> b - a).collect(Collectors.toList());
        return list.stream().findFirst().orElse(0);
    }

    public int addAllNum(int num) {
        String s = String.valueOf(num);
        int total = 0;
        for (int i = 0; i < s.length(); i++) {
            String integer = String.valueOf(s.charAt(i));
            total += Integer.parseInt(integer);
        }
        return total;
    }

    public int countBallsLeetCode(int lowLimit, int highLimit) {
        Map<Integer, Integer> map = new HashMap<>();
        int total = 0;
        for (int i = lowLimit; i <= highLimit; i++) {
            int num = digitSum(i);
            map.put(num, map.getOrDefault(num, 0) + 1);
            total = Math.max(total, map.get(num));
        }
        return total;
    }

    /**
     * 计算每个数相加
     * @param k
     * @return
     */
    public int digitSum(int k) {
        int ans = 0;
        while (k > 0) {
            ans += k % 10;
            k /= 10;
        }
        return ans;
    }
}
